#include "chmview.h"
#include "ui_chmview.h"
#include "qtreemodelhandler.h"

ChmView::ChmView(QWidget *parent) :
    AbstractView(parent),
    m_ui(new Ui::ChmView),webView(new QWebView)
{
    m_ui->setupUi(this);
    mainLayout = new QGridLayout;
    mainLayout->addWidget(webView, 0, 0);
    setLayout(mainLayout);

    webView->setHtml("",QUrl(""));
    webView->reload();
}
void ChmView::load(const QUrl &url){
    QString address("/");
    address.append(url.toString());
    QVector<QString>* contents = bookData->getIndexes();
    for(int i=0;i<contents->count();i++){
        if(address.startsWith(contents->at(i),Qt::CaseInsensitive)){
            webView->setHtml(bookData->getContents()->at(i),QUrl(""));
            webView->reload();
            break;
        }
    }
//    ((MainWindow*)this->parent())->getIndexDock()->setVisible(true);
//    ((MainWindow*)this->parent())->getIndexDock()->show();
    webView->setHtml("",QUrl(getCachedDir().append("index.html")));
    webView->reload();
}
void ChmView::load(const QString &url){
    CHMBookDataBuilder builder(url);
    if(url.endsWith(".chm",Qt::CaseInsensitive)){
        chmFileName = url;

        temp = new QTreeModel();
        QTreeModelHandler handler1(temp);
        builder.parse(handler1);

        QVector<QString>* contents = builder.getBookData()->getIndexes();
        QString conn;
        for(int i=0;i<contents->count();i++){
            conn.append(contents->at(i));
            conn.append("\n\t");
        }


        ((MainWindow*)parent())->setTreeViewModel(temp);
        bookData = builder.getBookData();
        if(conn.count()>0){
            webView->load(QUrl(getCachedDir().append("index.html")));
        }
        return;
    }

}
void ChmView::showNext(){

}
void ChmView::showPrevious(){

}
void ChmView::show(int index){

}
void ChmView::preview(){

}
ChmView::~ChmView()
{
    delete m_ui;
}

void ChmView::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
void ChmView::onShow(const QModelIndex &index){
    QVariant variant = temp->objectUrl(index);
    webView->load(QUrl(getCachedDir().append(variant.toString())));
    return;
}

QString ChmView::getCachedDir(){
    QFileInfo fileInfo(chmFileName);
    QString fileShortName;
    if(fileInfo.fileName().endsWith(".chm",Qt::CaseInsensitive)){
        fileShortName = fileInfo.fileName().left(fileInfo.fileName().length()-4);
    }

    QString appDir = QCoreApplication::applicationDirPath();
    QString path(appDir.append("/cache/"));
    path.append(fileShortName);
    path.append("/");

    return path;
}
